<script setup lang="ts">
import { request } from '@/api';
import { showLoadingToast, showToast, type ActionSheetAction } from 'vant';
import { ref, onMounted} from 'vue';
import b64toBlob from 'b64-to-blob';

const showAvatarSheet = ref(false)
const actions=[{name:'拍照'},{name:'相册'}]
const onCancel=()=>{
  showToast('已取消')
}
const onSelect= async (actions:ActionSheetAction,index:number)=>{
if(index===0){
// console.log('拍照')
const res = await mk.pickerCamera()
console.log('拍照',res)
}else if(index===1){
  // console.log('相册')
  const res = await mk.pickerPhoto()
  const img = b64toBlob(res,'image/jpeg')
  // console.log(img)
  
    showAvatarSheet.value = false
    // showLoadingToast({ message: '正在上传', duration: 0, forbidClick: true })
    // const image = base64ToBlob(data, 'image/jpeg')
    const fd = new FormData()
    fd.append('file', img, Date.now() + '.jpeg')
    const uploadRes = await request.post<MkResponse<{ avatar: string }>>('member/profile/avatar', fd)
    profile.value.avatar = uploadRes.data.result.avatar
    const user = mk.queryUser()
    user.avatar = uploadRes.data.result.avatar
    mk.updateUser(user)
    showToast({ message: '上传成功' })
  
    // showToast({ message: '上传失败' })
  
}
}

// 2. 选择生日日期
const showBirthdayPop = ref(false)
const currentDate = ref(['1998','8','2'])
const minDate = new Date(1970,1,1)
const maxDate = new Date(2025,1,1)
const onBirthdayConfirm = () => {
  console.log(currentDate.value)
  showBirthdayPop.value = false
  profile.value.birthday=currentDate.value.join('-')
}

// 3. 选择所在地
const areaList = ref<AreaColumns>({} as AreaColumns)
const showAreaPop = ref(false)
const selectArea = ref('')

onMounted(async () => {
  const res = await mk.getAreaColumns()
  areaList.value = res
  console.log(res)
})
const onAreaConfirm = ({selectedValues,selectedOptions}) => {
  // console.log(selectedValues)
  showAreaPop.value = false
  // console.log(selectedOptions)
  const arr = selectedOptions.map((v)=>{
  return v.text
  })
  // console.log(arr)
  profile.value.fullLocation = arr.join(' ')
  profile.value.provinceCode = selectedValues[0]
  profile.value.cityCode = selectedValues[1]
  profile.value.countyCode = selectedValues[2]
  // console.log( profile.value.countryCode)

}

//4.选择职业
const showJobPop = ref(false)
const selectJob = ref<string[]>([])
const columns = [
      { text: '医生', value: '医生' },
      { text: '护士', value: '护士' },
      { text: '老师', value: '老师' },
      { text: '学生', value: '学生' },
      { text: '会计师', value: '会计师' },
    ];
    const onJobConfirm = ({ selectedValues }) => {
      showJobPop.value=false
      // showToast(`当前值: ${selectedValues.join(',')}`)
      profile.value.profession = selectedValues.join('')
    };

    //获取用户信息
    const profile = ref({} as ProfileInfo)
    onMounted( async ()=>{
      const res = await request.get<MkResponse<ProfileInfo>>('/member/profile')
      profile.value=res.data.result
      currentDate.value=profile.value.birthday.split('-')
      selectJob.value = [profile.value.profession] 
    })

    //保存资料
    const onSubmit = async () =>{
      showLoadingToast({
        message:'正在更新'
      })
      const res = await request.put<MkResponse<ProfileInfo>>('/member/profile',profile.value)
      console.log(res)
      mk.updateUser(res.data.result)
      showToast('更新成功')
    }


</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image round width="100" height="100" class="avatar-img"
        :src="profile.avatar"
        @click="showAvatarSheet = true">
      </van-image>
      <div class="avatar-btn">
        <span @click="showAvatarSheet = true">修改头像</span>
      </div>
    </div>

<van-action-sheet
v-model:show="showAvatarSheet"
:actions="actions"
cancel-text="取消"
close-on-click-action
@cancel="onCancel"
@select="onSelect"
/>

    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field v-model="profile.account" label="账号" readonly></van-field>
      <van-field v-model="profile.nickname" label="昵称" placeholder="请输入昵称"></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group v-model="profile.gender" :icon-size="16">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field label="生日" readonly placeholder="请选择日期" @click="showBirthdayPop = true" v-model="profile.birthday"></van-field>
      <van-field label="所在地" readonly placeholder="请选择所在地" @click="showAreaPop = true" v-model="profile.fullLocation"></van-field>
      <van-field label="职业" readonly placeholder="请选择职业" @click="showJobPop = true" v-model="profile.profession"></van-field>
    </van-cell-group>

    <div class="submit">
      <van-button block type="primary" @click="onSubmit">
        保存资料 
      </van-button>
    </div>
  <van-popup v-model:show="showBirthdayPop" round position="bottom">
  <van-date-picker
   v-model:="currentDate" 
   title="选择日期" 
   :min-date="minDate"
   :max-date="maxDate"
   @confirm="onBirthdayConfirm"
   @cancel="showBirthdayPop = false" 
   />
</van-popup>

<van-popup v-model:show="showAreaPop" round position="bottom">
  <van-area
  v-model="selectArea"
  :area-list="areaList" 
  title="选择省市区"
  @confirm="onAreaConfirm"
  @cancel="showAreaPop=false"
  ></van-area>
</van-popup>

<van-popup v-model:show="showJobPop" round position="bottom">
  <van-picker
  v-model=selectJob
  title="标题"
  :columns="columns"
  @confirm="onJobConfirm"
  @cancel="showJobPop=false"
/>
</van-popup>

  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>